<template>
  <div>
    <!-- 搜索框 -->
    <div class="itemSearch">
      <!-- 查找名字 -->
      <form-input
        class="searchInput"
        placeholder="按项目名称搜索项目"
        v-model="filterText"
      >
      </form-input>
    </div>
    <!-- 项目展示框 -->
    <div class="itemContent">
      <el-table
        ref="multipleTable"
        :data="
          tables.slice(
            (this.currentPage - 1) * this.pageSize,
            this.currentPage * this.pageSize
          )
        "
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column
          prop="name"
          label="项目"
          width="520"
          :render-header="renderHeader"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <i class="el-icon-s-promotion"></i>
            <input
              type="text"
              v-focus
              :value="scope.row.name"
              class="itemRename"
              v-if="!scope.row.editeFlag"
              @blur="renameBlur(scope.$index, scope.row)"
            />
            <span v-show="scope.row.editeFlag">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="" width="80">
          <template slot-scope="scope">
            <div class="ignoreIcon">
              <i class="el-icon-more" @click="openEdit"></i>
              <div class="checkTop" v-show="editShow" @mouseleave="leave()">
                <div @click="clickRename(scope.$index, scope.row)">
                  <i class="el-icon-edit"></i> 项目重命名
                </div>
                <div @click="clickDelete(scope.$index, scope.row),open()">
                  <i class="el-icon-delete"></i> 删除项目
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="identification" label="标识" width="120">
        </el-table-column>
        <el-table-column
          prop="number"
          label="成员数"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <div class="number" @click="editeUser(scope.$index, scope.row)">
              <i class="el-icon-user" style="margin-right: 5px"></i>
              <span>{{ scope.row.number }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="creater"
          label="创建人"
          align="center"
          width="170"
        >
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" sortable>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页展示 -->
    <div class="itemPaging">
      <el-pagination
        background
        :page-size="pageSize"
        :current-page="currentPage"
        layout="total,prev, pager, next,jumper"
        :total="tables.length"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
    <!-- 添加项目弹出框 -->
    <div class="itemAlert" v-show="itemShow">
      <div class="itemForm">
        <i class="el-icon-close" id="close" @click="close()"></i>
        <f-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <form-item label="项目名称" prop="name" class="objectName">
            <form-input v-model="ruleForm.name" name="name"></form-input>
          </form-item>
          <form-item label="项目标识" prop="identification">
            <form-input
              v-model="ruleForm.identification"
              name="identification"
            ></form-input>
          </form-item>
          <form-item>
            <msg-button type="primary" @click="submitForm('ruleForm')"
              >添加</msg-button
            >
            <msg-button @click="resetForm('ruleForm')">重置</msg-button>
          </form-item>
        </f-form>
      </div>
    </div>
  </div>
</template>

<script>
import $ from "jquery";
import { mapMutations} from "vuex";
import {GetProjectItemAPI,AddProjectItemAPI,RenameItemAPI,BlurItemAPI,DeleteItemAPI} from '@/api/utils'
export default {
  data() {
    return {
      tableData: [],
      tableText:[],
      filterText: "",
      multipleSelection: [],
      pageSize: 5,
      currentPage: 1,
      itemShow: false,
      editShow: false,
      // 项目重命名
      itemNameShow: true,
      // 要删除的id
      deleteId:0,
      // 增加表单
      ruleForm: {
        name: "",
        identification: "",
      },
      // 表单中的相关规则配置
      rules: {
        name: [
          {
            required: true,
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        identification: [{ required: true, message: "请填写项目标识", trigger: "blur" ,message: "长度在 3 到 10 个字符",}],
      },
    };
  },
  // 注入依赖
  inject: ["reload"],
  async mounted(){
    const res = await GetProjectItemAPI()
    if (res.data.flag) {
            this.tableData = res.data.data
    }
  },
  methods: {
    // 页面刷新
    ...mapMutations("Refresh", { Show: "Show" }),
    // 展示列表第一列的选择框
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 当前页码
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
    },
    // 给表头添加图标
    renderHeader(h, { column }) {
      const that = this;
      return h("div", [
        h("span", column.label),
        h("i", {
          class: "el-icon-circle-plus-outline",
          style: "color:black;margin-left:5px;font-size:10px;cursor: pointer;",
          on: {
            click: function () {
              that.itemShow = true;
            },
          },
        }),
      ]);
    },
    // 项目增加表单的关闭
    close() {
      this.itemShow = false;
    },
    // 添加
    submitForm(formName) {
      // 获取点击下的时间
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      var nowDate = year + "-" + month + "-" + day;
      //表单验证
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //获取所有的表单中的内容
          var params = $(".demo-ruleForm").serializeArray();
          //    console.log(params);
          //把从表单获取过来的值存储为对象
          let array = {};
          params.forEach((element) => {
            array[element.name] = element.value;
          });
          // 创建者信息，后面要更新为当前登录管理员系统的账号
          array["creater"] = "高尚";
          array["createTime"] = nowDate;
          //把对象转换为 jsonp 格式
          array = JSON.stringify(array);
          return AddProjectItemAPI(array).then(res=>{
            if (res.data.flag) {
              // $('.demo-ruleForm').reset()
              this.itemShow = false;
              this.reload();
               this.$message.success('添加成功!');
            } else {
              this.$message.error(res.data.errorMsg);
            }
          })
        }
      });
    },
    // 页面刷新
    PageRefresh() {
      this.$nextTick(function () {
        this.$store.state.Refresh.isRouterAlive = true;
      });
    },
    // 点击省略号出现选择框
    openEdit() {
      this.editShow = !this.editShow;
    },
    // 鼠标移出
    leave() {
      this.editShow = false;
    },
    // 项目重命名
    async clickRename(index, row) {
      // console.log(row);
      row.editeFlag = false;
      return RenameItemAPI(row.id,row.name).then(res=>{
        if (res.data.flag) {
          //  this.reload()
           //请求成功
          }
      })
    },
    // 失去焦点不可命名
    async renameBlur(index, row) {
      let Rename = $('.itemRename').eq(index).val();
      row.editeFlag = true;
      return BlurItemAPI(row.id,Rename).then(res=>{
        if (res.data.flag) {
           this.reload()
           this.$message.success('修改成功!');
          }else{
             this.$message.error('修改失败!')
          }
      })
    },
    // 删除项目
    clickDelete(index, row) {
      this.deleteId = row.id
    },
    // 删除判断
    open() {
      this.$confirm("此操作将该项目永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.DeleteItem();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
          this.reload();
        });
    },
    // 项目删除操作
    async DeleteItem(){
      return DeleteItemAPI(this.deleteId).then(res=>{
        if (res.data.flag) {
            this.reload()
            this.$message.success('删除成功!');
          }else{
            this.$message.error('删除失败!');
          }
      })
    },
    editeUser(index,row){
      this.$store.commit('ItemAddUser/getItemId',row.id)
      this.$router.push({
      name: 'EditeUsertotal',
     })
    }
  },
  computed: {
    //  输入检索内容
    tables() {
      const filterText = this.filterText;
      if (filterText) {
        return this.tableData.filter((data) => {
          return Object.keys(data).some((key) => {
            if (key == "name") {
              return String(data[key]).indexOf(filterText) > -1;
            }
          });
        });
      }
      return this.tableData;
    },
    
  },
  // v-focus 聚焦
  directives: {
    focus: {
      inserted: function (el) {
        el.focus();
      },
    },
  },
};
</script>

<style scoped>
.itemSearch {
  height: 60px;
}
/* 项目前的图标颜色 */
.el-icon-s-promotion {
  color: #56abfb;
}
/* 项目变成 input 框 */
.itemRename {
  border: 1px solid #ccc;
  padding-left: 5px;
  outline: none;
}
/* 项目后面的省略符号 */
.el-icon-more {
  font-size: 8px;
  color: #348ee3;
  transform: rotate(90deg);
  cursor: pointer;
}
.ignoreIcon {
  display: none;
  text-align: center;
  width: 25px;
  height: 23px;
  border-radius: 3px;
  background-color: #e7f1f9;
}
/* 鼠标经过省略号显示 */
.itemContent /deep/ .el-table__body tr:hover .ignoreIcon {
  display: inline-block;
}
.checkTop {
  position: absolute;
  top: 45px;
  left: -136px;
  width: 170px;
  height: 70px;
  background-color: white;
  text-align: left;
  box-shadow: 0 0 12px 0 rgba(10, 10, 10, 0.3);
  z-index: 10;
}
.checkTop div {
  height: 35px;
  line-height: 35px;
  padding: 0 0 0 15px;
  cursor: pointer;
}
.checkTop div i {
  color: #ccc;
}
.checkTop div:hover {
  background-color: #f3f3f3;
}
.itemContent /deep/ .el-table__body-wrapper {
  height: 380px;
}
.itemContent /deep/ .el-table::before {
  background-color: transparent;
}
.itemContent /deep/ .el-table .el-table__cell {
  padding: 20px 0;
}
/* 配置分页 */
.itemPaging {
  position: fixed;
  bottom: 30px;
  left: 10%;
  width: 100%;
  height: 30px;
  /* margin-bottom: 0; */
  text-align: center;
}
/* 内容展示区域 */
.itemContent {
  width: 100%;
  min-height: 390px;
}
/* 增加项目表单 */
.itemAlert {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 99;
}
.itemForm {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 670px;
  max-height: 650px;
  background-color: white;
  padding-left: 135px;
  padding-top: 30px;
  box-sizing: border-box;
  border-radius: 15px;
}
.itemForm /deep/form input {
  margin: -3px;
}
.itemForm /deep/.el-form demo-ruleForm {
  width: 450px;
  height: 500px;
}
.itemForm /deep/.el-form-item__content {
  width: 300px;
}
#close {
  position: absolute;
  top: 5px;
  right: 5px;
  font-size: 20px;
  cursor: pointer;
  color: #ccc;
}
 /* 点击成员数 */
.number {
  cursor: pointer;
}
.itemContent /deep/.el-table .cell {
  color: #666;
}
.itemContent /deep/.twoLineCls {
  color:black;
}
.itemContent /deep/.el-table th.el-table__cell,
.itemContent /deep/.el-table tr,
.itemContent /deep/.el-table {
  background-color: rgba(255, 255, 255, 0.3);
}
</style>